<?php

namespace catchAdmin\basics\controller;

use app\command\Test;
use app\command\WeixinMessageQueue;
use catchAdmin\basics\model\Official as officialModel;
use catchAdmin\basics\model\OfficialLog;
use catcher\base\CatchRequest as Request;
use jzl\api\v1\Weixin;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use think\Request as ThinkRequest;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Goods as GoodsApi;

class Official extends CatchAdmin
{
    protected $redis;

    public function __construct(officialModel $officialModel)
    {
        $this->officialModel = $officialModel;
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
        $this->redis->auth(config('cache.stores.redis.password'));
    }

    //列表
    public function index(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->officialModel->getList($user['tenant_id']));
    }

    //创建
    public function create( CatchAuth $auth, Request $request)
    {
        $data = $request->post();
        $data['tenant_id'] = $auth->user()['tenant_id'];
        return CatchResponse::success($this->officialModel->storeBy($data));
    }

    //修改
    public function update($id, CatchAuth $auth, Request $request)
    {
        $data = $request->put();
        unset($data['created_at']);
        return CatchResponse::success($this->officialModel->updateBy($id, $data));
    }

    //删除
    public function delete($id, CatchAuth $auth, Request $request)
    {
        return CatchResponse::success($this->officialModel->deleteBy($id));
    }

    //同步
    public function remote_limit($id, CatchAuth $auth, Request $request){
        $res = (new \catchAdmin\basics\model\Official)->find($id);

        // 检查今日公众号数量限制
        $today = date('Y-m-d');
        $morning_key = 'weixin_official_limit:morning:' . $today;
        $afternoon_key = 'weixin_official_limit:afternoon:' . $today;

        // 获取当前时间判断是上午还是下午
        $current_hour = (int)date('H');
        $is_morning = $current_hour < 12;

        // 检查Redis中是否存在该公众号的记录
        $redis_key = 'weixin_official_v2:' . $res['official_name'];
        if ($this->redis->exists($redis_key)) {
            return CatchResponse::success([
                'count'=>0,
                'name'=>$res['official_name']
            ]);
        }

        // 检查时间段内的公众号数量限制
        if ($is_morning) {
            $official_count = (int)$this->redis->get($morning_key) ?: 0;
            if ($official_count >= 100) {
                return CatchResponse::success([
                    'count'=>0,
                    'name'=>$res['official_name']
                ]);
            }
        } else {
            $morning_count = (int)$this->redis->get($morning_key) ?: 0;
            $afternoon_count = (int)$this->redis->get($afternoon_key) ?: 0;
            $total_count = $morning_count + $afternoon_count;
            if ($total_count >= 200) {
                return CatchResponse::success([
                    'count'=>0,
                    'name'=>$res['official_name']
                ]);
            }
        }

        $weixinCommand = new WeixinMessageQueue;
        $all_list = $weixinCommand->last24hours($res['long_url'],$res['official_name']);
        $result = $weixinCommand->i($all_list, $res['official_name']);

        // 将处理过的公众号存入Redis，设置12小时过期
        $this->redis->set($redis_key, $res['long_url']);
        $this->redis->expire($redis_key, 43200);

        // 增加时间段内的公众号计数
        if ($is_morning) {
            $this->redis->incr($morning_key);
            $this->redis->expire($morning_key, 86400);
        } else {
            $this->redis->incr($afternoon_key);
            $this->redis->expire($afternoon_key, 86400);
        }

        return CatchResponse::success([
            'count'=> $result['success_count'],
            'name'=> $res['official_name']
        ]);
    }

    //无限制版本的remote
    public function remote($id, CatchAuth $auth, Request $request){
        $res = (new \catchAdmin\basics\model\Official)->find($id);
        
        $weixinCommand = new WeixinMessageQueue;
        $all_list = $weixinCommand->last24hours($res['long_url'],$res['official_name']);
        $result = $weixinCommand->i($all_list, $res['official_name']);

        return CatchResponse::success([
            'count'=> $result['success_count'],
            'name'=> $res['official_name']
        ]);
    }

//    public function sendTask($id, CatchAuth $auth, Request $request){
//        $task = new Test;
//        $task->
//    }
}